package cn.schoolwow.quickdao.module.database.ddl.query.flow.index;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.module.database.ddl.common.flow.SetHasResultSetFlow;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.Arrays;

public class HasIndexFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        String tableName = (String) flowContext.checkData("tableName");
        String indexName = (String) flowContext.checkData("indexName");

        flowContext.putTemporaryData("name", "判断索引是否存在");
        switch (databaseType){
            case H2:{
                flowContext.putTemporaryData("sql", "select index_name from information_schema.indexes where index_name = ?;");
                flowContext.putTemporaryData("parameters", Arrays.asList(indexName));
            }break;
            case SQLite:{
                flowContext.putTemporaryData("sql", "select name from sqlite_master where type = 'index' and name = ?;");
                flowContext.putTemporaryData("parameters", Arrays.asList(indexName));
            }break;
            case Mysql:
            case MariaDB:{
                flowContext.putTemporaryData("sql", "show index from " + quickDAOConfig.databaseContext.databaseProvider.escape(tableName) + " where key_name = ?;");
                flowContext.putTemporaryData("parameters", Arrays.asList(indexName));
            }break;
            case Postgresql:{
                flowContext.putTemporaryData("sql", "select indexname from pg_indexes where tablename = ? and indexname = ?;");
                flowContext.putTemporaryData("parameters", Arrays.asList(tableName, indexName));
            }break;
            case SQLServer:{
                flowContext.putTemporaryData("sql", "select name from sys.indexes WHERE object_id=OBJECT_ID(?, N'U') and name = ?;");
                flowContext.putTemporaryData("parameters", Arrays.asList(tableName, indexName));
            }break;
            case Oracle:{
                flowContext.putTemporaryData("sql", "select index_name from user_indexes where table_name = ? and index_name = ?");
                flowContext.putTemporaryData("parameters", Arrays.asList(tableName,indexName));
            }break;
        }
        flowContext.executeFlowList(new SetHasResultSetFlow(), new ExecuteQueryConnectionFlow());
    }

    @Override
    public String name() {
        return "索引是否存在";
    }
}
